package com.example.function;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.database.DatabaseHelper;
import com.example.pojo.Student;
import com.example.student.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddStudent extends AppCompatActivity {

    // 视图组件
    private EditText etStudentId, etStudentName, etStudentAge, etStudentPhone, etStudentGrade;
    private Button btnSubmit;

    private DatabaseHelper databaseHelper;
    private Spinner spinnerCollege, spinnerMajor,spinnerGrade ;

    private Map<String, List<String>> collegeMajorMap = new HashMap<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_student); // 绑定布局文件
        databaseHelper = new DatabaseHelper(this);
        // 初始化视图
        initViews();
        initCollegeMajorData();

        // 设置学院 Spinner 的适配器
        ArrayAdapter<String> collegeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, new ArrayList<>(collegeMajorMap.keySet()));
        collegeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCollege.setAdapter(collegeAdapter);

        // 监听学院 Spinner 的选择事件
        spinnerCollege.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedCollege = (String) parent.getItemAtPosition(position);
                updateMajorSpinner(selectedCollege);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        // 设置提交按钮点击事件
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addStudentToDatabase();
            }
        });
    }

    /**
     * 初始化视图
     */
    private void initViews() {
        etStudentId = findViewById(R.id.etStudentId);
        etStudentName = findViewById(R.id.etStudentName);
        etStudentAge = findViewById(R.id.etStudentAge);
        etStudentPhone = findViewById(R.id.etStudentPhone);
        spinnerGrade = findViewById(R.id.spinnerGrade);
        btnSubmit = findViewById(R.id.btnSubmit);
        spinnerCollege = findViewById(R.id.spinnerCollege);
        spinnerMajor = findViewById(R.id.spinnerMajor);
    }

    /**
     * 添加学生信息到数据库
     */
    private void addStudentToDatabase() {
        // 获取输入内容
        String studentId = etStudentId.getText().toString().trim();
        String name = etStudentName.getText().toString().trim();
        String ageStr = etStudentAge.getText().toString().trim();
        String college = spinnerCollege.getSelectedItem().toString();
        String major = spinnerMajor.getSelectedItem().toString();
        String phone = etStudentPhone.getText().toString().trim();
        String grade = etStudentGrade.getText().toString().trim();

        // 校验输入
        if (studentId.isEmpty() || name.isEmpty() || ageStr.isEmpty() || college.isEmpty() || major.isEmpty() || phone.isEmpty() || grade.isEmpty()) {
            Toast.makeText(this, "请填写完整信息", Toast.LENGTH_SHORT).show();
            return;
        }
        // 校验学号是否为 8 位数字
        if (studentId.length() != 8 || !studentId.matches("\\d+")) {
            Toast.makeText(this, "学号必须为 8 位数字", Toast.LENGTH_SHORT).show();
            return;
        }

        // 校验年龄是否为 2 位数字
        if (ageStr.length() != 2 || !ageStr.matches("\\d+")) {
            Toast.makeText(this, "请输入正确的年龄！", Toast.LENGTH_SHORT).show();
            return;
        }
        // 校验手机号是否为 2 位数字
        if (phone.length() <= 11 || !ageStr.matches("\\d+")) {
            Toast.makeText(this, "请输入正确的手机号！", Toast.LENGTH_SHORT).show();
            return;
        }

        int age = Integer.parseInt(ageStr); // 将年龄转换为整数


        // 创建 Student 对象
        Student student = new Student(studentId, name, age, college, major,  phone, grade);
        student.setPassword("123456");
        student.setRole("student");

        // 插入数据库
        boolean isSuccess = databaseHelper.insertStudent(student);
        if (isSuccess) {
            Toast.makeText(this, "添加成功", Toast.LENGTH_SHORT).show();
            finish(); // 关闭当前页面
        } else {
            Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 初始化学院和专业数据
     */
    private void initCollegeMajorData() {
        collegeMajorMap = new HashMap<>();
        collegeMajorMap.put("计算机科学与技术", List.of("物联网工程", "计算机科学与技术", "网络安全"));
        collegeMajorMap.put("商学院", List.of("工商管理", "市场营销", "会计学"));
        collegeMajorMap.put("文学院", List.of("汉语言文学", "新闻学"));
        collegeMajorMap.put("理学院", List.of("数学与应用数学", "物理学", "化学"));
        collegeMajorMap.put("工程学院", List.of("机械工程", "电气工程", "土木工程"));
        collegeMajorMap.put("医学院", List.of("临床医学", "口腔医学", "药学"));
        collegeMajorMap.put("艺术学院", List.of("音乐学", "美术学", "设计学"));
        collegeMajorMap.put("法学院", List.of("法学", "知识产权", "国际法"));
        collegeMajorMap.put("教育学院", List.of("教育学", "心理学", "学前教育"));
        collegeMajorMap.put("农学院", List.of("农学", "园艺学", "植物保护"));

        // 初始化年级数据
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.grade_array, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerGrade.setAdapter(adapter);

    }
    private void updateMajorSpinner(String college) {
        List<String> majors = collegeMajorMap.get(college);
        ArrayAdapter<String> majorAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, majors);
        majorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerMajor.setAdapter(majorAdapter);
    }
}